//
//  DownloadManager.swift
//  dkqsy
//
//  Created by Macintosh on 2024/1/6.
//

import UIKit
import Alamofire
import Photos

class DownloadManager: NSObject {

    static func saveVideo(url: URL) {
        topViewController?.showHUD()
        let fileName = "video_download_\(Int(Date().timeIntervalSince1970))"
        let filePath = URL(fileURLWithPath: NSTemporaryDirectory() + "\(fileName).mp4")
        let destination: DownloadRequest.Destination = { _, _ in
            return (filePath, [.removePreviousFile, .createIntermediateDirectories])
        }
        AF.download(url, to: destination).response { _ in
            DispatchQueue.main.async {
                PHPhotoLibrary.shared().performChanges {
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: filePath)
                } completionHandler: { isSuccess, error in
                    DispatchQueue.global(qos: .background).async {
                        if FileManager.default.fileExists(atPath: filePath.path) {
                            try? FileManager.default.removeItem(atPath: filePath.path)
                        }
                    }
                    Async.main {
                        topViewController?.hideHUD()
                        topViewController?.showTips(isSuccess ? "保存成功" : "保存失败")
                        if isSuccess {
                            requestEventSave(title: "视频保存到本地", mode: "视频保存到本地")
                        }
                    }
                }
            }
        }
    }
    
    static func saveImageToAlbum(_ url: URL, showTips: Bool = true) {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let data = data {
                PHPhotoLibrary.shared().performChanges({
                    let request = PHAssetCreationRequest.forAsset()
                    let options = PHAssetResourceCreationOptions()
                    options.shouldMoveFile = true
                    request.addResource(with: .photo, data: data, options: options)
                }) { (success, error) in
                    if showTips {
                        Async.main {
                            topViewController?.showTips(success ? "保存成功" : "保存失败")
                        }
                    }
                }
                return
            }
            if showTips {
                Async.main {
                    topViewController?.showTips("保存失败")
                }
            }
        }
        task.resume() // 开始下载任务
    }

    static func saveImage(image: UIImage, showTips: Bool = true) {
        PHPhotoLibrary.shared().performChanges {
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        } completionHandler: { isSuccess, error in
            if showTips {
                Async.main {
                    topViewController?.showTips(isSuccess ? "保存成功" : "保存失败")
                }
            }
        }
    }
    
}
